package com.example.fallback;

import com.tedu.utll.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * hystrix 降级处理    默认集成  比如对商品服务进行处理
 * 不需要配置   zuul自动配置hystrix
 */
@Component   //自动配置
public class ItemFallBack implements FallbackProvider {

    /**
     * 指定哪个服务使用降级代码
     * 返回服务的id  item-service
     *  返回：* null  对所有的服务使用降级
     * @return
     */
    @Override
    public String getRoute() {
        //对商品服务进行降级
        return "item-service";
    }

    /**
     * 返回的降级响应   数据   response
     * @param route
     * @param cause
     * @return   可以返回缓存中数据，比如redis
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        //http
        return new ClientHttpResponse() {
            @Override
            public HttpHeaders getHeaders() {

                HttpHeaders h = new HttpHeaders();
                h.add("Content-Type", "text/html;charset=UTF-8");

                return h;
            }

            /**
             * 返回内容
             * @return
             * @throws IOException
             */
            @Override
            public InputStream getBody() throws IOException {

                String s = JsonResult.err().code(500).msg("服务器错误，进行降级").toString();

                return new ByteArrayInputStream(s.getBytes("UTF-8"));
            }

            // 状态码  200  ok
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            //状态值   200
            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.value(); //  500
            }

            //  ok
            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();  //INTERNAL_SERVER_ERROR
            }

            //关闭流    ByteArrayInputStream是内存数组，不占用底层系统的资源   释放资源
            @Override
            public void close() {

            }
        };
    }
}
